package com.njtoyo.taxi.admin.library.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njtoyo.taxi.admin.logic.business.simple_call.SimpleCallBackLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallBacklog;
import com.njtoyo.taxi.admin.mapper.master.enums.SimpleCallBacklogState;
import com.njtoyo.taxi.admin.mapper.master.mapper.SimpleCallBacklogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class SimpleCallBacklogRunner implements ApplicationRunner {

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    @Autowired
    private SimpleCallBacklogMapper simpleCallBacklogMapper;

    @Autowired
    private SimpleCallBackLogic simpleCallBackLogic;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        QueryWrapper<SimpleCallBacklog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", SimpleCallBacklogState.init)
                .gt("system_send_timestamp", DateUtil.currentSeconds());
        List<SimpleCallBacklog> backlogs = simpleCallBacklogMapper.selectList(queryWrapper);
        log.info("项目重启时获取需发送的电召数据 {}", backlogs);
        if (!Objects.isNull(backlogs)) {
            backlogs.forEach(backlog -> {
                taskScheduler.schedule(() -> {
                    simpleCallBackLogic.sendSimpleCallBacklog(backlog.getId());
                }, DateUtil.date(backlog.getSystemSendTimestamp() * 1000));
            });
        }
    }
}
